package com.ai.module.chat.util;

import com.ai.module.chat.config.advice.exception.BusinessException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;





/**
 * @author: heJinQin
 * @create: 2024-02-24 11:48
 * @description:
 **/

public class Base64Util {

    /**
     * 文件转 base64字符串
     *
     * @param imageFileList 图片文件
     * @return base64ImageList base64字符串集合
     */
    public static List<String> file2Base64(List<File> imageFileList) {
        List<String> base64ImageList = new ArrayList<>();
        imageFileList.forEach(imageFile -> {
            doDealImage2Base64(imageFile, base64ImageList);
        });
        return base64ImageList;
    }

    public static void doDealImage2Base64(File imageFile, List<String> base64ImageList) {
        try (InputStream inputStream = new FileInputStream(imageFile)) {
            byte[] buffer = new byte[inputStream.available()];
            // 将输入流内容存入字节数组buffer
            int bytesRead = inputStream.read(buffer);
            if (bytesRead != -1) {
                // 创建Base64对象并进行编码
                String imageBase64Str = Base64.getEncoder().encodeToString(buffer);
                base64ImageList.add(imageBase64Str);
            } else {
                System.err.println("无法读取图像文件！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * base64转 图片
     *
     * @param base64String
     * @param fileType     jpg
     */
    public static File base2Image(String base64String, String fileType) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            // String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            // String imageFileName = DateUtils.getTransDateTime() +"."+ fileType;
            base64String = base64String
                    .replaceAll("data:image/png;base64,", "")
                    .replaceAll("data:image/jpeg;base64,", "");
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            File imageFile = File.createTempFile(DateUtils.getTransDateTime(), ".jpg");
            //new File(imageFileName);
            //写入生成文件
            ImageIO.write(bufferedImage, fileType, imageFile);
            return imageFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


//    public static void main(String[] args) throws Exception {
//        String url = "https://public-gpt.oss-cn-shenzhen.aliyuncs.com/ai-product/worker/%E8%81%8C%E4%B8%9A/%E6%B4%BB%E5%8A%A8%E7%AD%96%E5%88%92.png";
//        String a =  getBase64ByUrl(url);
//        System.out.println(a);
//    }

    /**
     * 根据图片链接转为base64数据
     *
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static String getBase64ByUrl(String imageUrl)  {
        try {
            URL url = new URL(imageUrl);
            // 打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式为"GET"
            conn.setRequestMethod("GET");
            // 超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            // 得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = readInputStream(inStream);
            Base64.Encoder encode = Base64.getEncoder();

            byte[] encode1 = encode.encode(data);

            String realBase64 = new String(encode1);
            return "data:image/jpeg;base64," + realBase64;
        }catch (Exception ex){
            ex.printStackTrace();
            throw new BusinessException("图片URL转base664异常:" + ex.getMessage());
        }
        // new一个URL对象

    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    public static void main(String[] args) throws Exception {
//        String url = "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